import { NextRequest } from 'next/server';

// Nodemailer
import nodemailer, { SendMailOptions } from 'nodemailer';

// React-email
import { render } from '@react-email/render';

import SendPdfEmail from '@/app/components/templates/email/SendPdfEmail';

// Variables
import { NODEMAILER_EMAIL, NODEMAILER_PW } from '@/lib/variables';

import { fileToBuffer } from '@/lib/helpers';

// Nodemailer transporter
const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: NODEMAILER_EMAIL,
        pass: NODEMAILER_PW,
    },
});

export const sendPdfToEmailService = async (req: NextRequest) => {
    const fd = await req.formData();

    // Get form data values
    const email = fd.get('email') as string;
    const invoicePdf = fd.get('invoicePdf') as File;
    const invoiceNumber = fd.get('invoiceNumber') as string;

    // Get email html content
    const emailHTML = await render(SendPdfEmail({ invoiceNumber }));

    // Convert file to buffer
    const invoiceBuffer = await fileToBuffer(invoicePdf);

    try {
        const mailOptions: SendMailOptions = {
            from: 'Invoify',
            to: email,
            subject: `Invoice Ready: #${invoiceNumber}`,
            html: emailHTML,
            attachments: [
                {
                    filename: 'invoice.pdf',
                    content: invoiceBuffer,
                },
            ],
        };

        await transporter.sendMail(mailOptions);
        return true;
    } catch (error) {
        console.error('Error sending email', error);
        return false;
    }
};
